<?php
namespace app\api\controller;

use app\api\Base;
use think\Config;
use think\Db;
use baseutils\BaseUtil;
use com\gdl\newagk\interfaces\UserServiceClient;
use com\gdl\newagk\dataobject\user\UserRequestDTO; 
use com\gdl\newagk\dataobject\user\UserLoginRequestDTO; 
use com\gdl\newagk\dataobject\user\UserPasswordRequestDTO; 
use com\gdl\newagk\dataobject\user\RePasswordRequestDTO; 
use com\gdl\newagk\dataobject\action\LoginRequestDTO;
use com\gdl\newagk\interfaces\ActionServiceClient;
use com\gdl\newagk\dataobject\user\RegisterRequestDTO;
use com\gdl\newagk\dataobject\user\UserDTO;

/**
 * app用户相关接口 包含登录 修改密码 选择平台
 * @author tc 2018/04/12
 */

class User extends Base
{
 	/** 
 	 *  用户登录 支持 手机号 验证码 身份证登录
 	 *  @return JSON [description] 400失败 200成功
 	 */
	public function appUserLogin() 
    {
    	$msg = ['code'=>400, 'msg'=>'登录失败', 'data'=>[]];
        header('Access-Control-Allow-Origin:*');
        // 响应类型  
        header('Access-Control-Allow-Methods:POST');
        // 响应头设置  
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        $username = $this->request->param('username') ? $this->request->param('username') : "";
        $password = $this->request->param('password') ? $this->request->param('password') : "";
        $way = $this->request->param('way') ? getStr($this->request->param('way')) : 1; 

        if(empty($username)){
            $msg['msg'] = "用户名不能为空";
            return json_encode($msg);
        }
        if(empty($password)){
            $msg['msg'] = "密码不能为空";
            return json_encode($msg);   
        }
        try { 
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $loginRequestDo = new LoginRequestDTO();
            $loginRequestDo->username = $username;
            $loginRequestDo->password = $password;
            $loginRequestDo->way = $way;
            $username = $loginRequestDo->username;

            $util = new BaseUtil(); 
            if ($util->IsMobile($username)) {
                $loginRequestDo->type = 'mobile';
            } elseif ($util->isIdCard($username)) {
                $loginRequestDo->type = 'idcard';
            } else {
                $loginRequestDo->type = 'username';
            }

            $UserService = new ActionServiceClient(NULL);
            \ApiClient::build($UserService);

            $result = $UserService->login($loginRequestDo); 

            if ($result->success == TRUE) {
            	$msg['msg'] = $result->message;
                $msg['code'] = $result->code?$result->code:400;
                $msg['data'] = $result->data;
                if ($result->code == 200) {
                    session('uid', $result->uid);
                    $msg['code'] = $result->code?$result->code:400;
                    $msg['msg'] = $result->message;
                }
            } else {
                $msg['msg'] = "登录失败";
            }

        } catch (Exception $ex) {
            $msg['msg'] = $ex->getMessage();
        }
        return json_encode($msg);
    }
    
    /** 
 	 *  手机验证码登录 
     *	第一步：发送验证码
 	 *  @return JSON [description] 400失败 200成功
 	 */
    public function appUserCode(){
    	$msg = ['code'=>400, 'msg'=>'请带入正确的手机号', 'data'=>[]];
    	$phone = $this->request->param("phone") ? $this->request->param("phone") : "";
    	$type = $this->request->param("code") ? $this->request->param("code") : "login"; # 默认获取登录验证码 传入repassword忘记密码找回密码
        $gdl_userid = $this->request->param("gdl_userid") ? $this->request->param("gdl_userid") : ""; # 修改手机号
    	if(!is_mobile($phone)){
    		return json_encode($msg);
    	}

    	\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
    	$UserService = new UserServiceClient(NULL);
    	\ApiClient::build($UserService);
    	$userDO = new UserPasswordRequestDTO();
    	$userDO->phone = $phone;
    	$userDO->code = $type;
        $userDO->userid = $gdl_userid;

    	$result = $UserService->appUserCode($userDO);
    	if($result->success==true){
    		$msg['code'] = $result->code;
    		// $msg['data'] = $result->data[1];
            $msg['msg'] = $result->message;
            $msg['data'] = $result->data[0];   
                if($result->code ==200){
                    $msg['data'] = $result->data[1];    
                }
    		
    	}

    	return json_encode($msg);
    }

     /** 
 	 *  手机验证码登录 
     *	第二步：验证验证码
 	 *  @return JSON [description] 400失败 200成功
 	 */
    public function appUserNameLogin(){
    	$msg = ['code'=>400, 'msg'=>'验证失败','data'=>[]];

    	$phone = $this->request->param("phone") ? $this->request->param("phone") : ""; 
    	$userid = $this->request->param("userid") ? $this->request->param("userid") : ""; 
    	$code = $this->request->param("code") ? $this->request->param("code") : ""; 
    	if(!$phone && !$userid && !$code){
    		$msg['msg'] = "缺少必要参数";
    		return json_encode($msg);
    	}
    	try{
	    	\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
	    	$UserService = new UserServiceClient(NULL);
	    	\ApiClient::build($UserService);
	    	$userDO = new UserPasswordRequestDTO();
	    	$userDO->phone = $phone;
	    	$userDO->code = $code;
	    	$userDO->userid = $userid;
	    	$result = $UserService->appUserNameLogin($userDO);
            // var_dump($result);exit;
	    	if($result->success==true){
	    		$msg['code'] = $result->code?$result->code:400;
	    		$msg['msg'] = $result->message;
                $msg['data'] = $result->data[0];   
                if($result->code ==200){
                    $msg['data'] = $result->data[1];   
                    $msg['msg'] = $result->message;
                }
	    		
	    	}
    	}catch(Exception $e){
    		$msg['msg'] = $e->getMessage(); 
    	}
    	return json_encode($msg);
    }

    /** 
 	 *  手机验证码找回密码
     *	验证验证码并修改密码
 	 *  @return JSON [description] 400失败 200成功
 	 */
 	public function appUserPassword(){
 		$msg = ['code'=>400, 'msg'=>'修改失败','data'=>[]];
		$phone = $user->phone ? gdl_lib_BaseUtils::getStr($user->phone) : ""; 
        $code = $user->code ? gdl_lib_BaseUtils::getStr($user->code) : ""; 
 		$password = $this->request->param("password") ? $this->request->param("password") : "";
 		$repassword = $this->request->param("repassword") ? $this->request->param("repassword") : "";
 		$userid = $this->request->param("userid") ? $this->request->param("userid") : "";

 		if(!$password && !$repassword && !$userid && !$phone && !$code){
    		$msg['msg'] = "缺少必要参数";
    		return json_encode($msg);
    	}

    	try{
	    	\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
	    	$UserService = new UserServiceClient(NULL);
	    	\ApiClient::build($UserService);
	    	$userDO = new RePasswordRequestDTO();
	    	$userDO->password = $password;
	    	$userDO->repassword = $repassword;
	    	$userDO->userid = $userid;
	    	$result = $UserService->appUserPassword($userDO);
	    	if($result->success==true){
	    		$msg['code'] = $result->code;
	    		$msg['msg'] = $result->message;
	    		$msg['data'] = $result->data[0];   
                if($result->code ==200){
                    $msg['data'] = $result->data[1];    
                }
	    	}
    	}catch(Exception $e){
    		$msg['msg'] = $e->getMessage(); 
    	}
    	return json_encode($msg);
 	}
 	/** 
 	 *  手机验证码找回密码
     *	验证验证码并修改密码
 	 *  @return JSON [description] 400失败 200成功
 	 */
 	public function registerUser(){
 		$msg = ['code'=>400, 'msg'=>'注册失败','data'=>[]];

 		$truename = $this->request->param("truename") ? $this->request->param("truename") : ""; # 真实姓名
 		$username = \CUtf8PY::encode($truename,'all'); # 拼音账号

 		$password = $this->request->param("password") ? $this->request->param("password") : ""; # 第一次密码
 		$repassword = $this->request->param("repassword") ? $this->request->param("repassword") : ""; # 重复密码
 		$mobile = $this->request->param("mobile") ? $this->request->param("mobile") : ""; # 手机号码
 		$idcard = $this->request->param("idcard") ? $this->request->param("idcard") : ""; # 
 		$way = $this->request->param("way") ? $this->request->param("way") : 1;
 		$account_type = $this->request->param("account_type") ? $this->request->param("account_type") : 1;
 		$code = $this->request->param("code") ? $this->request->param("code") : "";

        // $truename = "唐川";
        // $username = \CUtf8PY::encode($truename,'all'); # 拼音账号
        // $password = "123456";
        // $repassword = "123456";
        // $mobile = "13883121541";
        // $idcard = "513723199409192914";
        // $code = "614165";
        if(!$username){
            $username = $mobile;
        }
 		if(!$truename && !$password && !$repassword && !$mobile && !$idcard && !$code){
    		$msg['msg'] = "缺少必要参数";
    		return json_encode($msg);
    	}
    	if($password!=$repassword){
    		$msg['msg'] = "两次密码不一致";
    		return json_encode($msg);
    	}
    	if(!is_mobile($mobile)){
    		$msg['msg'] = "请绑定正确的手机号码";
    		return json_encode($msg);
    	}
        $util = new BaseUtil();
        if(!$util->isIdCard($idcard)){
            $msg['msg'] = "请输入正确的身份证号码";
            return json_encode($msg);   
        }
    	try{
	    	\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
	    	$UserService = new UserServiceClient(NULL);
	    	\ApiClient::build($UserService);
	    	$userDO = new RegisterRequestDTO();
	    	$userDO->username = $username;
	    	$userDO->password = $password;
	    	$userDO->truename = $truename;
	    	$userDO->mobile = $mobile;
	    	$userDO->idcard = $idcard;
	    	$userDO->way = $way;
	    	$userDO->code = $code;
	    	$userDO->account_type = $account_type;

	    	$result = $UserService->registerUser($userDO); 
	    	if($result->success==true){
	    		$msg['code'] = $result->code;
	    		$msg['msg'] = $result->message;
	    		$msg['data'] = $result->data[1]?$result->data[1]:[];
	    	}
    	}catch(Exception $e){
    		$msg['msg'] = $e->getMessage(); 
    	}
    	return json_encode($msg);
 	}

    /**
    * 修改用户logo
    */
   public function appAddLogo(){
        $msg = ['code'=>400,'msg'=>'上传头像失败', 'data'=>[]];
        if (!empty($_FILES)) {
            $type = str_ireplace(array('img', 'images', 'image', '/'), '', $_FILES['file']['type']);
            if (in_array($type, array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
                $result = \Qiniu::instance()->upload(); //七牛上传
                $address = $result[0]['key'];
                $identity_id = $this->request->param('identity_id') ? $this->request->param('identity_id') : 0;
                if ($address != '' && $identity_id) {

                    $path = config("qiniu.QINIU_DOMAIN") . $address;
                    $model = Db::name('User');
                    $modelUserCompany = Db::name('UserCompany');
                    $userid = $modelUserCompany->where(array('id' => $identity_id, 'status' => 0))->field('userid')->limit(1)->select();
                    $userid = $userid[0]['userid'];
                    $sql = "UPDATE agk_user  SET photo='{$path}' where userId='{$userid}'";
                    $model->execute($sql);

                    $msg['msg'] = "上传成功";
                    $msg['code'] = 200;
                    $msg['data'] = ['path'=>$path];
                }
            }
        }
        return json_encode($msg);
   }

   /**
    * 退出平台
    */
   public function appExitPlaform(){
        $msg = ['code'=>400, 'msg'=>'退出平台失败','data'=>[]];
        $identity_id = $this->request->param("identity_id") ? $this->request->param("identity_id") : ""; #compan
        $plaformId = $this->request->param("plaform_id") ? $this->request->param("plaform_id") : ""; #compan 
        if(empty($identity_id) || empty($plaformId)){
            $msg['msg'] = "缺少必要参数";
            return json_encode($msg);
        }

        try{
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $UserService = new UserServiceClient(NULL);
            \ApiClient::build($UserService);
            $userDO = new UserDTO();
            $userDO->identity_id = $identity_id;
            $userDO->id = $plaformId;
            // var_dump($UserService);exit;
            $result = $UserService->appExitPlaform($userDO);
            if($result->code == 200){
                $msg['msg'] = $result->message;
                $msg['code'] = 200;
            }
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage(); 
        }
        return json_encode($msg);
   }

   /**
    * 修改用户 姓名 账号 身份证号
    */
   public function appEditUser(){
        $msg = ['code'=>400, 'msg'=>"修改失败" , 'data'=>[]];
        $truename = $this->request->param("truename") ? $this->request->param("truename") : "";
        $username = $this->request->param("username") ? $this->request->param("username") : "";
        $idcard = $this->request->param("idcard") ? $this->request->param("idcard") : "";
        $plaformId = $this->request->param("plaform_id") ? $this->request->param("plaform_id") : "";
        $userid = $this->request->param("userid") ? $this->request->param("userid") : "";
        $gdl_userid = $this->request->param("gdl_userid") ? $this->request->param("gdl_userid") : "";
        $identity_id = $this->request->param("identity_id") ? $this->request->param("identity_id") : "";

        # 判断身份证是否正确
        if($idcard){
            $util = new BaseUtil();
            if(!$util->isIdCard($idcard)){
                $msg['msg'] = "请输入正确的身份证";
                return json_encode($msg);
            }    
        }

        try{

            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $UserService = new UserServiceClient(NULL);
            \ApiClient::build($UserService);
            $userDO = new UserDTO();
            $userDO->id = $plaformId;
            $userDO->userid = $userid;
            $userDO->gdl_userid = $gdl_userid;
            $userDO->identity_id = $identity_id;
            $userDO->data = ['truename'=>$truename, 'username'=>$username, 'idcard'=>$idcard];

            $result = $UserService->appEditUser($userDO);
            if($result->success == true){
                $msg['code'] = $result->code;
                $msg['msg'] = $result->message;
                $msg['data'] = [];//$result->data;
            }

        }catch(Exception $ex){
            $msg['msg'] = $ex->getMessage();
        }
        
        return json_encode($msg);
   }

   /**
    * 修改手机号码
    */
   public function appEditPhone(){
        $msg = ['code'=>400, 'msg'=>"修改失败" , 'data'=>[]];
        $phone = $this->request->param("phone") ?  $this->request->param("phone") : "";
        $code = $this->request->param("code") ?  $this->request->param("code") : "";
        $gdl_userid = $this->request->param("gdl_userid") ?  $this->request->param("gdl_userid") : "";

        if(empty($phone) || empty($code) || empty($gdl_userid)){
            $msg['msg'] = "缺少必要参数";
            return json_encode($msg);
        }
        try{
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $UserService = new UserServiceClient(NULL);
            \ApiClient::build($UserService);
            $userDO = new UserDTO();
            $userDO->phone = $phone;
            $userDO->code = $code;
            $userDO->userid = $gdl_userid;
            $result = $UserService->appEditPhone($userDO);
            if($result->success == true){
                $msg['code'] = $result->code;
                $msg['msg'] = $result->message; 
            }
        }catch(Exception $ex){
            $msg['msg'] = $ex->getMessage();   
        }

        return json_encode($msg);
    }

    /**
     * 根据旧密码修改密码
     */
    public function appEditPassword(){
        $msg = ['code'=>400, 'msg'=>"修改失败" , 'data'=>[]];
        $oldpassword = $this->request->param("oldpassword") ?  $this->request->param("oldpassword") : "";
        $password = $this->request->param("password") ?  $this->request->param("password") : "";
        $repassword = $this->request->param("repassword") ?  $this->request->param("repassword") : "";
        $gdl_userid = $this->request->param("gdl_userid") ?  $this->request->param("gdl_userid") : "";

        if($password!=$repassword){
            $msg['msg'] = "两次密码不一致";
            return json_encode($msg);
        }

        if(empty($oldpassword) || empty($password) || empty($repassword) || empty($gdl_userid)){
            $msg['msg'] = "缺少必要参数";
            return json_encode($msg);
        }
        try{
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $UserService = new UserServiceClient(NULL);
            \ApiClient::build($UserService);
            $userDO = new UserDTO();
            $userDO->data = ['oldpassword'=>$oldpassword, 'password'=>$password, 'repassword'=>$repassword];
            $userDO->userid = $gdl_userid;
            $result = $UserService->appEditPassword($userDO);
            if($result->success == true){
                $msg['code'] = $result->code;
                $msg['msg'] = $result->message; 
            }
        }catch(Exception $ex){
            $msg['msg'] = $ex->getMessage();   
        }

        return json_encode($msg);
    }


}
